package com.sfx.shortLink.common.utils;


import org.springframework.beans.BeanInstantiationException;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-11-15
 * Time: 15:34
 */
public class BeanUtils {

    /**
     * 将sourceList 转化为目标类的List
     *
     * @param sourceList  源list
     * @param targetClass 目标类
     * @param <K>         源类
     * @param <T>         目标类
     * @return 返回目标类的list
     */
    public static <K, T> List<T> convertList(List<K> sourceList, Class<T> targetClass) {
        return cn.hutool.core.bean.BeanUtil.copyToList(sourceList, targetClass);
    }

    /**
     * 将一个对象转成目标对象
     *
     * @param source
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> T convert(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        T t = newInstance(targetClass);
        org.springframework.beans.BeanUtils.copyProperties(source, t);
        return t;
    }

    private static <T> T newInstance(Class<T> targetClass) {
        try {
            return targetClass.newInstance();
        } catch (Exception e) {
            throw new BeanInstantiationException(targetClass, "instantiation error", e);
        }
    }

//    /**
//     * 将List对象转换成目标对象，注意实现是ArrayList
//     *
//     * @param targetClass
//     * @param <K>
//     * @param <T>
//     * @return
//     */
//    public static <K, T> List<T> convertList(List<K> sourceList, Class<T> targetClass) {
//        if (sourceList == null) {
//            return null;
//        }
//        List targetList = new ArrayList((int)(sourceList.size()/0.75) + 1);
//        for (K source : sourceList) {
//            targetList.add(convert(source, targetClass));
//        }
//        return targetList;
//    }
//
//    private static <T> T newInstance(Class<T> targetClass) {
//        try {
//            return targetClass.newInstance();
//        } catch (Exception e) {
//            throw new BeanInstantiationException(targetClass, "instantiation error", e);
//        }
//    }
}